import router, { asyncRoutes } from './router'
import store from './store'

const whiteList = ['/login', '/404']

// 处理一级路由权限数据
function getFirstRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    return item.split(':')[0]
  })
  return [...new Set(newArr)]
}

// 处理二级路由权限数据
function getSecondRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return [...new Set(newArr)]
}

// 根据权限标识过滤路由表
function getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes) {
  // 根据一级和二级对动态路由表做过滤 return出去过滤之后的路由表
  // 1. 根据一级路由对动态路由表做过滤
  return asyncRoutes.filter(route => {
    return firstRoutePerms.includes(route.permission)
  }).map(item => {
    // console.log('过滤路由', item)

    // 2. 对二级路由做过滤
    return {
      ...item,
      children: item.children.filter(item => secondRoutePerms.includes(item.permission))
    }
  })
}

// 路由前置守卫 (每次路由跳转之前)
router.beforeEach(async(to, from, next) => {
  // 判断token是否存在
  if (store.getters.token) {
    // token存在&访问登录页 -> 拦截到首页
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.getters.profile.id) {
        // 获取原始权限列表
        const { permissions } = await store.dispatch('user/getProfile')
        // console.log('原始权限列表', permissions)

        // 1. 数据处理得到一级路由菜单标识
        const firstRoutePerms = getFirstRoutePerms(permissions)
        let filterRoutes = []
        // * 管理员权限
        if (firstRoutePerms.includes('*')) {
          console.log('管理员')
          filterRoutes = [...asyncRoutes]
        } else {
        // 2. 数据处理得到二级路由菜单标识
          const secondRoutePerms = getSecondRoutePerms(permissions)
          // console.log(secondRoutePerms)
          filterRoutes = getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes)
        }
        router.addRoutes(filterRoutes)
        // 5. 存入Vuex渲染左侧菜单
        store.commit('menu/setMenuList', filterRoutes)
        next({ ...to, replace: true })
      } else {
        next()
        return
      }
    }
  } else {
    // 不存在
    // 判断访问的是否是白名单路径
    // console.log(222)

    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
